import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Lesson, LessonFormData, PaginationResponse, QueryParams } from '@/types/admin'
import { api, API_ENDPOINTS, type ApiResponse } from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useLessonStore = defineStore('lesson', () => {
  // 状态
  const lessons = ref<Lesson[]>([])
  const featuredLessons = ref<Lesson[]>([])
  const recentLessons = ref<Lesson[]>([])
  const currentLesson = ref<Lesson | null>(null)
  const pagination = ref({
    page: 1,
    limit: 20,
    total: 0,
    pages: 0
  })
  const isLoading = ref(false)

  // 辅助函数：处理标签数据
  const processTags = (tags: string | string[] | undefined): string[] => {
    console.log('processTags 输入:', tags, '类型:', typeof tags, '是否为数组:', Array.isArray(tags))
    
    if (!tags) {
      console.log('tags 为空，返回空数组')
      return []
    }
    
    if (typeof tags === 'string') {
      console.log('tags 是字符串，进行分割处理')
      const result = tags.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0)
      console.log('字符串处理结果:', result)
      return result
    }
    
    if (Array.isArray(tags)) {
      console.log('tags 是数组，进行过滤处理')
      const result = tags.filter(tag => tag && tag.trim().length > 0)
      console.log('数组处理结果:', result)
      return result
    }
    
    console.log('tags 类型未知，返回空数组')
    return []
  }

  // 获取课程列表
  const fetchLessons = async (params: QueryParams = {}) => {
    try {
      isLoading.value = true
      const response = await api.get<Lesson[]>(API_ENDPOINTS.LESSONS, params)
      
      if (response.data) {
        lessons.value = response.data
        if (response.pagination) {
          const { total, page, limit } = response.pagination;
          const pages = Math.ceil(total / limit);
          pagination.value = { total, page, limit, pages };
        }
      }
    } catch (error) {
      console.error('获取课程列表失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 获取推荐课程
  const fetchFeaturedLessons = async (limit: number = 10) => {
    try {
      const response = await api.get<Lesson[]>(API_ENDPOINTS.LESSONS_FEATURED, { limit })
      if (response.data) {
        featuredLessons.value = response.data
      }
    } catch (error) {
      console.error('获取推荐课程失败:', error)
      throw error
    }
  }

  // 获取最新课程
  const fetchRecentLessons = async (limit: number = 10) => {
    try {
      const response = await api.get<Lesson[]>(API_ENDPOINTS.LESSONS_RECENT, { limit })
      if (response.data) {
        recentLessons.value = response.data
      }
    } catch (error) {
      console.error('获取最新课程失败:', error)
      throw error
    }
  }

  // 获取课程详情
  const fetchLessonById = async (id: number) => {
    try {
      isLoading.value = true
      const response = await api.get<Lesson>(`${API_ENDPOINTS.LESSONS}/${id}`)
      if (response.data) {
        currentLesson.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取课程详情失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 根据slug获取课程
  const fetchLessonBySlug = async (slug: string) => {
    try {
      isLoading.value = true
      const response = await api.get<Lesson>(API_ENDPOINTS.LESSON_BY_SLUG(slug))
      if (response.data) {
        currentLesson.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取课程详情失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建课程
  const createLesson = async (lessonData: LessonFormData) => {
    try {
      console.log('创建课程 - 请求数据:', lessonData)
      
      // 确保必填字段存在
      if (!lessonData.title) {
        throw new Error('课程标题不能为空')
      }
      if (!lessonData.slug) {
        throw new Error('课程标识不能为空')
      }
      if (!lessonData.categoryId) {
        throw new Error('请选择课程分类')
      }
      if (!lessonData.content) {
        throw new Error('课程内容不能为空')
      }
      
      // 处理数据类型转换和可选字段
      const data: any = {
        title: lessonData.title,
        slug: lessonData.slug,
        content: lessonData.content,
        // 确保数值类型字段为整数
        categoryId: Number(lessonData.categoryId),
        difficulty: lessonData.difficulty,
        duration: lessonData.duration && Number(lessonData.duration) > 0 ? Number(lessonData.duration) : undefined,
        sortOrder: lessonData.sortOrder ? Number(lessonData.sortOrder) : 0,
        // 确保布尔类型字段
        isPublished: Boolean(lessonData.isPublished),
        isFeatured: Boolean(lessonData.isFeatured),
        // 处理标签字段 - 后端期望数组格式
        tags: processTags(lessonData.tags),
        excerpt: lessonData.excerpt || '',
        author: lessonData.author || '',
        metaKeywords: lessonData.metaKeywords || '',
        metaDescription: lessonData.metaDescription || ''
      }
      
      // 只有当coverImage有值时才添加到请求中
      if (lessonData.coverImage && lessonData.coverImage.trim()) {
        let coverImageUrl = lessonData.coverImage.trim()
        
        // 如果是完整的URL，转换为相对路径
        if (coverImageUrl.startsWith('http://localhost:3001/')) {
          coverImageUrl = coverImageUrl.replace('http://localhost:3001/', '/')
        } else if (coverImageUrl.startsWith('https://localhost:3001/')) {
          coverImageUrl = coverImageUrl.replace('https://localhost:3001/', '/')
        }
        
        // 确保以 / 开头
        if (coverImageUrl && !coverImageUrl.startsWith('/')) {
          coverImageUrl = '/' + coverImageUrl
        }
        
        data.coverImage = coverImageUrl
        
        console.log('创建课程 - 封面图片处理:', {
          原始值: lessonData.coverImage,
          处理后: data.coverImage
        })
      }
      
      const response = await api.post<ApiResponse<Lesson>>('/lessons', data)
      console.log('创建课程 - 响应数据:', response)
      console.log('响应数据结构:', {
        hasData: !!response.data,
        hasDataData: !!response.data?.data,
        responseData: response.data,
        message: response.data?.message
      })
      
      // 检查不同的响应数据结构
      if (response.data?.data) {
        // 标准格式：{ data: { data: Lesson } }
        lessons.value = [response.data.data, ...lessons.value]
        return response.data.data
      } else if (response.data && typeof response.data === 'object' && 'id' in response.data) {
        // 直接返回课程对象：{ data: Lesson }
        const lessonData = response.data as unknown as Lesson
        lessons.value = [lessonData, ...lessons.value]
        return lessonData
      } else if (response.message === '课程创建成功') {
        // 只有消息，没有数据，但创建成功
        console.log('课程创建成功，但没有返回课程数据')
        return null
      }
      
      throw new Error('创建课程失败')
    } catch (error: any) {
      console.error('创建课程失败:', error)
      console.error('错误响应数据:', error.response?.data)
      console.error('发送的数据:', lessonData)
      throw error
    }
  }

  // 更新课程
  const updateLesson = async (id: number, lessonData: Partial<LessonFormData>) => {
    try {
      console.log('更新课程 - 原始数据:', { id, ...lessonData })
      
      // 创建干净的数据对象，只包含有效字段
      const data: any = {}
      
      // 处理字符串字段
      if (lessonData.title !== undefined && lessonData.title !== null) {
        const title = String(lessonData.title).trim()
        if (title) {
          data.title = title
        }
      }
      if (lessonData.slug !== undefined && lessonData.slug !== null) {
        const slug = String(lessonData.slug).trim()
        if (slug) {
          data.slug = slug
          data.skipSlugCheck = true // 更新时跳过slug检查
        }
      }
      if (lessonData.content !== undefined && lessonData.content !== null) {
        const content = String(lessonData.content).trim()
        if (content) {
          data.content = content
        }
      }
      if (lessonData.excerpt !== undefined) {
        const excerpt = lessonData.excerpt ? String(lessonData.excerpt).trim() : ''
        data.excerpt = excerpt
      }
      if (lessonData.author !== undefined) {
        const author = lessonData.author ? String(lessonData.author).trim() : ''
        data.author = author
      }
      if (lessonData.metaKeywords !== undefined) {
        const metaKeywords = lessonData.metaKeywords ? String(lessonData.metaKeywords).trim() : ''
        data.metaKeywords = metaKeywords
      }
      if (lessonData.metaDescription !== undefined) {
        const metaDescription = lessonData.metaDescription ? String(lessonData.metaDescription).trim() : ''
        data.metaDescription = metaDescription
      }
      
      // 处理数值字段
      if (lessonData.categoryId !== undefined) {
        data.categoryId = Number(lessonData.categoryId)
        if (isNaN(data.categoryId) || data.categoryId <= 0) {
          throw new Error('分类ID无效')
        }
      }
      if (lessonData.duration !== undefined && lessonData.duration !== null) {
        const duration = Number(lessonData.duration)
        if (!isNaN(duration) && duration > 0) {
          data.duration = duration
        }
      }
      if (lessonData.sortOrder !== undefined) {
        data.sortOrder = Number(lessonData.sortOrder) || 0
      }
      
      // 处理布尔字段
      if (lessonData.isPublished !== undefined) {
        data.isPublished = Boolean(lessonData.isPublished)
      }
      if (lessonData.isFeatured !== undefined) {
        data.isFeatured = Boolean(lessonData.isFeatured)
      }
      
      // 处理难度字段
      if (lessonData.difficulty !== undefined) {
        data.difficulty = lessonData.difficulty
      }
      
      // 处理封面图片字段
      if (lessonData.coverImage !== undefined) {
        if (lessonData.coverImage && lessonData.coverImage.trim()) {
          let coverImageUrl = lessonData.coverImage.trim()
          
          // 如果是完整的URL，转换为相对路径
          if (coverImageUrl.startsWith('http://localhost:3001/')) {
            coverImageUrl = coverImageUrl.replace('http://localhost:3001/', '/')
          } else if (coverImageUrl.startsWith('https://localhost:3001/')) {
            coverImageUrl = coverImageUrl.replace('https://localhost:3001/', '/')
          }
          
          // 确保以 / 开头
          if (coverImageUrl && !coverImageUrl.startsWith('/')) {
            coverImageUrl = '/' + coverImageUrl
          }
          
          data.coverImage = coverImageUrl
          
          console.log('封面图片处理:', {
            原始值: lessonData.coverImage,
            处理后: data.coverImage
          })
        } else {
          data.coverImage = null // 明确设置为null而不是undefined
        }
      }
      
      // 处理标签字段
      if (lessonData.tags !== undefined) {
        data.tags = processTags(lessonData.tags)
      }
      
      console.log('更新课程 - 处理后数据:', data)
      console.log('更新课程 - 数据字段详情:', {
        title: data.title,
        slug: data.slug,
        categoryId: data.categoryId,
        difficulty: data.difficulty,
        content: data.content ? `${data.content.substring(0, 50)}...` : undefined,
        coverImage: data.coverImage,
        tags: data.tags,
        isPublished: data.isPublished,
        isFeatured: data.isFeatured,
        duration: data.duration,
        sortOrder: data.sortOrder,
        excerpt: data.excerpt,
        author: data.author,
        metaKeywords: data.metaKeywords,
        metaDescription: data.metaDescription,
        skipSlugCheck: data.skipSlugCheck
      })
      
      const response = await api.put<ApiResponse<Lesson>>(`${API_ENDPOINTS.LESSONS}/${id}`, data)
      console.log('更新课程 - 响应数据:', response)
      
      if (response.data?.data) {
        const updatedLesson = response.data.data
        const index = lessons.value.findIndex(l => l.id === id)
        if (index !== -1) {
          lessons.value[index] = updatedLesson
        }
        if (currentLesson.value?.id === id) {
          currentLesson.value = updatedLesson
        }
        return updatedLesson
      }
      
      return null
    } catch (error: any) {
      console.error('更新课程失败:', error)
      throw error
    }
  }

  // 删除课程
  const deleteLesson = async (id: number) => {
    try {
      await api.delete(`${API_ENDPOINTS.LESSONS}/${id}`)
      lessons.value = lessons.value.filter(l => l.id !== id)
      if (currentLesson.value?.id === id) {
        currentLesson.value = null
      }
      ElMessage.success('课程删除成功')
    } catch (error) {
      console.error('删除课程失败:', error)
      throw error
    }
  }

  // 批量删除课程
  const deleteLessonsBatch = async (ids: number[]) => {
    try {
      await Promise.all(ids.map(id => api.delete(`${API_ENDPOINTS.LESSONS}/${id}`)))
      lessons.value = lessons.value.filter(l => !ids.includes(l.id))
      ElMessage.success(`成功删除 ${ids.length} 个课程`)
    } catch (error) {
      console.error('批量删除课程失败:', error)
      throw error
    }
  }

  // 切换课程发布状态
  const toggleLessonPublishStatus = async (id: number, isPublished: boolean) => {
    try {
      const response = await api.put<Lesson>(`${API_ENDPOINTS.LESSONS}/${id}`, { isPublished })
      if (response.data) {
        const index = lessons.value.findIndex(l => l.id === id)
        if (index !== -1) {
          lessons.value[index] = response.data
        }
        ElMessage.success(`课程已${isPublished ? '发布' : '下架'}`)
        return response.data
      }
    } catch (error) {
      console.error('切换课程发布状态失败:', error)
      throw error
    }
  }

  // 切换推荐状态
  const toggleLessonFeaturedStatus = async (id: number, isFeatured: boolean) => {
    try {
      const response = await api.put<Lesson>(`${API_ENDPOINTS.LESSONS}/${id}`, { isFeatured })
      if (response.data) {
        const index = lessons.value.findIndex(l => l.id === id)
        if (index !== -1) {
          lessons.value[index] = response.data
        }
        ElMessage.success(`课程${isFeatured ? '已推荐' : '取消推荐'}`)
        return response.data
      }
    } catch (error) {
      console.error('切换推荐状态失败:', error)
      throw error
    }
  }

  // 点赞课程
  const likeLesson = async (id: number) => {
    try {
      const response = await api.post<{ message: string; likeCount: number }>(
        API_ENDPOINTS.LESSON_LIKE(id)
      )
      if (response.data) {
        const index = lessons.value.findIndex(l => l.id === id)
        if (index !== -1) {
          lessons.value[index].likeCount = response.data.likeCount
        }
        if (currentLesson.value?.id === id) {
          currentLesson.value.likeCount = response.data.likeCount
        }
        ElMessage.success(response.message || '点赞成功')
      }
    } catch (error) {
      console.error('点赞失败:', error)
      throw error
    }
  }

  // 清除当前课程
  const clearCurrentLesson = () => {
    currentLesson.value = null
  }

  // 重置状态
  const reset = () => {
    lessons.value = []
    featuredLessons.value = []
    recentLessons.value = []
    currentLesson.value = null
    pagination.value = {
      page: 1,
      limit: 20,
      total: 0,
      pages: 0
    }
    isLoading.value = false
  }

  return {
    // 状态
    lessons,
    featuredLessons,
    recentLessons,
    currentLesson,
    pagination,
    isLoading,

    // 方法
    fetchLessons,
    fetchFeaturedLessons,
    fetchRecentLessons,
    fetchLessonById,
    fetchLessonBySlug,
    createLesson,
    updateLesson,
    deleteLesson,
    deleteLessonsBatch,
    toggleLessonPublishStatus,
    toggleLessonFeaturedStatus,
    likeLesson,
    clearCurrentLesson,
    reset
  }
}) 